package com.qf.xiaomi.web.servlet;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.druid.util.StringUtils;
import com.qf.xiaomi.pojo.Address;
import com.qf.xiaomi.pojo.User;
import com.qf.xiaomi.service.AddressService;
import com.qf.xiaomi.service.UserService;
import com.qf.xiaomi.service.impl.AddressServiceImpl;
import com.qf.xiaomi.service.impl.UserServiceImpl;
import com.qf.xiaomi.web.base.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();

    /*
    public String login(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("登录");

        return "forward:/index.jsp";
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("退出");
        try {
            resp.getWriter().write("ajax响应前端");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String register(HttpServletRequest req, HttpServletResponse resp){
        return "redirect:/index.jsp";
    }
    */
    AddressService addressService = new AddressServiceImpl();

    /**
     * 设置 默认收货地址
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public String defaultAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取 地址ID
        String aId = req.getParameter("id");

        User user = (User) req.getSession().getAttribute("user");

        addressService.setDefaultAddress(user.getId(), aId);


        //修改之后，重新查询地址列表页面
        return "redirect:/userservlet?method=getAddress";
    }
    public String updateAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //获取参数数据
        int id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String detail = req.getParameter("detail");
        //封装数据
        Address address = new Address();
        address.setId(id);
        address.setName(name);
        address.setDetail(detail);
        address.setPhone(phone);
        //更新数据
        addressService.updateAddress(address);

        //更新之后，重新查询地址列表页面
        return "redirect:/userservlet?method=getAddress";
    }

    public String deleteAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        int id = Integer.parseInt(req.getParameter("id"));
        //删除地址
        addressService.deleteById(id);

        //新增之后，重新查询地址列表页面
        return "redirect:/userservlet?method=getAddress";
    }

    public String addAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String detail = req.getParameter("detail");
        //获取该用户的 购物车信息
        User user = (User) req.getSession().getAttribute("user");
        int uid = user.getId();

        Address address = new Address();
        address.setUid(uid);
        address.setName(name);
        address.setDetail(detail);
        address.setPhone(phone);
        address.setLevel(0);
        addressService.addAddress(address);

        //新增之后，重新查询地址列表页面
        return "redirect:/userservlet?method=getAddress";
    }

    public String getAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //获取该用户的 购物车信息
        User user = (User) req.getSession().getAttribute("user");

        //获取 地址列表
        List<Address> addList = addressService.getAddrList(user.getId());
        //把数据存储到 请求域
        req.setAttribute("addList", addList);
        //请求转发到 前端
        return "forward:/self_info.jsp";
    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws Exception
     */
    public String logOut(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //清空session
        req.getSession().invalidate();

        //跳转到登录页面
        return "redirect:/login.jsp";
    }

    /**
     * 登录功能
     * @param req
     * @param resp
     * @throws Exception
     */
    public String login(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //是否自动登录
        String auto = req.getParameter("auto");

        // 根据用户名和密码查询用户对象
        User user = userService.findByUserAndPwd(username, password);
        if(user == null){
            //如果user为null，则登录失败
            return "redirect:/login.jsp";
        }else {
            //否则登录成功
            //保存登录状态
            req.getSession().setAttribute("user",  user);

            //保存登录状态到cookie中
            if("on".equalsIgnoreCase(auto)) {
                //对 用户名和密码进行 数据转换
                String encode = URLEncoder.encode(username + "#" + password, "utf-8");
                //创建cookie对象
                Cookie cookie = new Cookie("user", encode);

                cookie.setDomain("localhost"); //设置域名
                cookie.setPath("/"); //设置 在任意路径下都可以获取cookie
                cookie.setMaxAge(14 * 24 * 60 * 60);  //设置有效期为两周
                resp.addCookie(cookie);
            }

            //跳转到首页
            return "redirect:/index.jsp";
        }


    }

    /**
     * 校验验证码
     * @param req
     * @param resp
     * @throws Exception
     */
    public void checkCode(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //获取用户输入的验证码
        String inputCode = req.getParameter("code");
        PrintWriter writer = resp.getWriter();
        //从session中获取验证码
        Object codeObj = req.getSession().getAttribute("code");
        if(codeObj == null) {
            writer.write("1");
        }else {
            String code = (String) codeObj;
            if(code.equalsIgnoreCase(inputCode)){
                writer.write("0");
            }else {
                writer.write("1");
            }
        }

    }


    /**
     * 获取验证码
     * @param req
     * @param resp
     * @return
     */
    public void code(HttpServletRequest req, HttpServletResponse resp) throws Exception{

        //创建验证码对象
        ValidateCode validateCode = new ValidateCode(111, 37, 2, 20);

        //在session中存储验证码
        HttpSession session = req.getSession();
        session.setAttribute("code", validateCode.getCode());


        //把验证码 输出到  响应对象的输出流（前端）
        validateCode.write(resp.getOutputStream());
    }


    /**
     * 注册功能
     * 1. 获取前端请求的参数
     * 2. 保存到数据库
     * 3. 响应前端(
     *      注册成功，跳转到登录页面
     *      注册失败， 跳转到注册页面
     * )
     * @param req
     * @param resp
     * @return
     */
    public String register(HttpServletRequest req, HttpServletResponse resp){
        //获取 请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String gender = req.getParameter("gender");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setGender(gender);

        // 调用service ，保存到数据库
        boolean isSuccess = userService.register(user);
        //如果注册成功，跳转登录页面
        if(isSuccess) {
            return "redirect:/login.jsp";
        } else {
            //否则，跳转到注册页面
            return "redirect:/register.jsp";
        }

    }

    /**
     * 校验用户名 是否存在
     *  1. 获取 username 参数
     *  2. 如果username为空，则返回 0
     *  3. 查询数据库， 如果存在，返回1
     *  4. 如果不存在，返回2
     * @param req
     * @param resp
     */
    public void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取参数
        String username = req.getParameter("username");
        PrintWriter writer = resp.getWriter();
        //判断 如果为空，返回0
        if(StringUtils.isEmpty(username)) {
            writer.write("0");
        } else {
            //username 不为空， 则根据username查询数据库
            User user  = userService.findByUsername(username);
            if(user == null) {
                //如果username 在数据库不存在，则返回2
                writer.write("2");
            }else {
                //如果username 在数据库存在，则返回1
                writer.write("1");
            }
        }


    }
}
